<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item prop="scheduleName">
        <el-input
          v-model="queryParams.scheduleName"
          placeholder="请输入计划编号/名称"
          clearable
          @keyup.enter.native="handleQuery"
          class="my-input"
        />
      </el-form-item>
      <el-form-item prop="scheduleSourceType">
        <el-select
          v-model="queryParams.scheduleSourceType"
          placeholder="请选择订单来源"
          class="my-input"
          clearable
        >
          <el-option
            v-for="dict in getScheduleSource"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="schedulePdCode">
        <el-select
          v-model="queryParams.schedulePdCode"
          placeholder="请选择产品"
          class="my-input"
          clearable
        >
          <el-option
            v-for="dict in goods"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="scheduleStatus">
        <el-select
          v-model="queryParams.scheduleStatus"
          placeholder="请选择状态"
          class="my-input"
          clearable
        >
          <el-option
            v-for="dict in getScheduleStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="scheduleStart">
        <el-date-picker clearable
                        v-model="queryParams.scheduleStart"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开工时间"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item prop="scheduleComplete">
        <el-date-picker clearable
                        v-model="queryParams.scheduleComplete"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择完工时间"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item prop="scheduleRequire">
        <el-date-picker clearable
                        v-model="queryParams.scheduleRequire"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择需求日期"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:schedule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pro:schedule:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pro:schedule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" fixed />
      <el-table-column label="计划编号" align="center" prop="scheduleCode" width="150" fixed show-overflow-tooltip />
      <el-table-column label="计划名称" align="center" prop="scheduleName" width="120" fixed show-overflow-tooltip />
      <el-table-column label="工单数量" align="center" prop="scheduleWorkNum" width="100">
        <template slot-scope="scope">
          {{ scope.row.scheduleWorkNum ? scope.row.scheduleWorkNum : '0' }}
        </template>
      </el-table-column>
      <el-table-column label="来源类型" align="center" prop="scheduleSourceType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="getScheduleSource" :value="scope.row.scheduleSourceType" />
        </template>
      </el-table-column>
      <el-table-column label="成品名称" align="center" prop="gbsGood.pdName" width="100" show-overflow-tooltip />
      <el-table-column label="成品编号" align="center" prop="gbsGood.pdCode" width="100" show-overflow-tooltip />
      <el-table-column label="规格型号" align="center" prop="gbsGood.pdSpecType" show-overflow-tooltip />
      <el-table-column label="单位" align="center" prop="gbsGood.gbsGoodUnit.guName" show-overflow-tooltip />
      <el-table-column label="计划数量" align="center" prop="scheduleNum" width="100" />
      <el-table-column label="计划开工时间" align="center" prop="scheduleStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduleStart) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" prop="scheduleComplete" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduleComplete) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="需求日期" align="center" prop="scheduleRequire" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduleRequire) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center"
                       prop="scheduleStatus" fixed="right"
      >
        <template slot-scope="scope">
          <dict-tag :options="getScheduleStatus" :value="scope.row.scheduleStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.scheduleStatus !== '0'"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pro:schedule:query']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pro:schedule:remove']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['pro:schedule:edit']"
                       v-if="scope.row.scheduleStatus === '0' || scope.row.scheduleStatus === '1'"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleUpdate" icon="el-icon-edit"
                                v-hasPermi="['pro:schedule:edit']"
                                v-if="scope.row.scheduleStatus === '0'"
              >修改
              </el-dropdown-item>
              <el-dropdown-item command="handleDecompose" icon="el-icon-edit"
                                v-hasPermi="['pro:schedule:edit']"
              >分解工单
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--    工单拆分-->
    <el-dialog title="拆分生产工单" :visible.sync="decomposeScheduleDialog" width="50%"
    >
      <div>
        <div class="my-table-header-row my-table-row">
          <div style="width: 5%">序号</div>
          <div style="width: 35%">工单名称</div>
          <div style="width: 35%">生产数量</div>
          <div style="width: 15%">操作</div>
        </div>
        <draggable v-model="dragWorkOrderData" @end="handleMoveEndWorkOrder" handle=".draggable-btn"
                   :options="{group:{name: 'itxst',pull:true},sort: true}"
        >
          <div v-for="(item, index) in workOrderData" :key="index" class="my-table-row">
            <div style="width: 5%">
              {{ index + 1 }}
            </div>
            <div style="width: 35%">
              <el-input v-model="item.workOrderName" style="width: 120px" />
            </div>
            <div style="width: 35%">
              <el-input-number v-model.number="item.workOrderNum" style="width: 120px" :min="1"
              />
            </div>
            <div style="width: 15%">
              <el-button
                size="mini"
                type="text"
                @click="handleRemoveWorkOrder(index)"
              >移除
              </el-button>
              <el-button
                size="mini"
                type="text"
                class="draggable-btn"
                style="cursor:move;"
              >拖拽合并工单
              </el-button>
            </div>
          </div>
        </draggable>
      </div>

      <div style="text-align: center;">
        <el-button
          size="small"
          type="text"
          @click="handleAddWorkOrder"
          icon="el-icon-plus"
        >
          添加工单
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDecompose">取 消</el-button>
        <el-button type="primary" @click="handleOkDecompose">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { conditionSchedule, decomposeSchedule, delSchedule, getOrders, listSchedule } from '@/api/yyj/pro/schedule'
import { parseTime } from '@/utils/ruoyi'
import { formatDate } from '@/utils'

export default {
  name: 'Schedule',
  dicts: ['yyj_schedule_source', 'yyj_schedule_status'],
  components: {
    draggable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划表格数据
      scheduleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schedulePdCode: null,
        scheduleName: null,
        scheduleNum: null,
        scheduleStatus: null,
        scheduleStart: null,
        scheduleComplete: null,
        scheduleRequire: null,
        scheduleSourceType: null,
        scheduleOrder: null,
        scheduleCloseReason: null,
        scheduleWorkNum: null,
        scheduleBom: null,
        scheduleDesc: null
      },
      // 查询条件中的goods
      goods: [],
      // 分解计划dialog
      decomposeScheduleDialog: false,
      // 工单信息
      workOrderData: [],
      dragWorkOrderData: [],
      // 当前的schedule
      currentSchedule: {},
      // 当前增长的id
      currentIndex: 0
    }
  },
  computed: {
    getScheduleStatus() {
      return this.dict.type.yyj_schedule_status
    },
    getScheduleSource() {
      return this.dict.type.yyj_schedule_source
    }
  },
  created() {
    Promise.all([this.getList(), this.getCondition()])
  },
  methods: {
    parseTime,
    /** 查询生产计划列表 */
    async getList() {
      this.loading = true
      const res = await listSchedule(this.queryParams)
      console.log('res ', res)
      this.scheduleList = res.rows
      this.total = res.total
      this.loading = false
    },
    // 查询生产计划条件
    async getCondition() {
      const res = await conditionSchedule()
      this.goods = res.data
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scheduleCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: `/pro/schedule-change`
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const scheduleCode = row.scheduleCode || this.ids
      this.$router.push({
        path: `/pro/schedule-change/${scheduleCode}`
      })
    },
    // 查看详情
    handleDetail(row) {
      this.$router.push({
        path: `/pro/schedule-detail/${row.scheduleCode}`
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scheduleCodes = row.scheduleCode || this.ids
      this.$modal.confirm('是否确认删除生产计划编号为"' + scheduleCodes + '"的数据项？').then(function() {
        return delSchedule(scheduleCodes)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/schedule/export', {
        ...this.queryParams
      }, `schedule_${new Date().getTime()}.xlsx`)
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleUpdate':
          this.handleUpdate(row)
          break
        case 'handleDecompose':
          this.handleDecompose(row)
          break
        default:
          break
      }
    },
    // 分解计划
    async handleDecompose(row) {
      this.currentIndex = 0
      this.currentSchedule = row
      // 判断状态
      if (this.currentSchedule.scheduleStatus === '1') {
        // 发送请求，获取工单
        const res = await getOrders(this.currentSchedule.scheduleCode)
        if (!res.data || res.data.length <= 0) {
          await this.$tab.refreshPage()
        } else {
          this.workOrderData = [...res.data]
        }
      } else {
        ++this.currentIndex
        this.workOrderData = [{
          scheduleCode: this.currentSchedule.scheduleCode,
          workOrderName: '生产工单' + this.currentIndex,
          workOrderNum: this.currentSchedule.scheduleNum,
          workOrderStatus: '0',
          workOrderProduct: this.currentSchedule.schedulePdCode,
          workOrderBom: this.currentSchedule.scheduleBom,
          workOrderBVersion: this.currentSchedule.scheduleBomVersion,
          // 批次号 年月日 + 编号
          workOrderBatch: formatDate(Date.now()).substring(0, 10).replace('-', '') + this.currentIndex,
          workOrderRoute: this.currentSchedule.pdProuteCode,
          workOrderRequire: this.currentSchedule.scheduleRequire
        }]
      }
      this.dragWorkOrderData = [...this.workOrderData]
      this.decomposeScheduleDialog = true
    },
    // 添加生产工单
    handleAddWorkOrder() {
      ++this.currentIndex
      this.workOrderData.push({
        scheduleCode: this.currentSchedule.scheduleCode,
        workOrderName: '生产工单' + this.currentIndex,
        workOrderNum: 1,
        workOrderStatus: '0',
        workOrderProduct: this.currentSchedule.schedulePdCode,
        workOrderBom: this.currentSchedule.scheduleBom,
        workOrderBVersion: this.currentSchedule.scheduleBomVersion,
        // 批次号 年月日 + 编号
        workOrderBatch: formatDate(Date.now()).substring(0, 10).replace('-', '') + this.currentIndex,
        workOrderRoute: this.currentSchedule.pdProuteCode,
        workOrderRequire: this.currentSchedule.scheduleRequire
      })
    },
    // 移除生产工单
    handleRemoveWorkOrder(index) {
      if (this.workOrderData.length <= 1) {
        this.$modal.msgError('最小工单数为1')
        return
      }
      const spliceWorkOrder = this.workOrderData.splice(index, 1)
      // 拆分份数
      const part = this.workOrderData.length
      // 每份多少
      const numsOfPart = Math.floor(parseInt(spliceWorkOrder[0].workOrderNum) / part)
      // 循环添加
      for (let i = 0; i < this.workOrderData.length - 1; i++) {
        this.workOrderData[i].workOrderNum = parseInt(this.workOrderData[i].workOrderNum) + numsOfPart
      }
      // 最后的需要加1是否
      const reduce = this.workOrderData.reduce((acc, cur) => acc + parseInt(cur.workOrderNum), 0)
      this.workOrderData[this.workOrderData.length - 1].workOrderNum = parseInt(this.workOrderData[this.workOrderData.length - 1].workOrderNum) + (reduce + numsOfPart < this.currentScheduleTotal ? numsOfPart + 1 : numsOfPart)
    },
    // 拖动之后
    handleMoveEndWorkOrder(e) {
      if (this.workOrderData.length <= 1) {
        return
      }
      let { oldIndex, newIndex } = e
      if (oldIndex === newIndex) {
        return
      }
      if (oldIndex - 1 > newIndex) {
        oldIndex--
      }
      if (this.workOrderData[oldIndex] && this.workOrderData[newIndex] && this.workOrderData[oldIndex].workOrderNum != null && this.workOrderData[newIndex].workOrderNum != null) {
        let oldRow = this.workOrderData[oldIndex]
        this.workOrderData[newIndex].workOrderNum = parseInt(this.workOrderData[newIndex].workOrderNum) + parseInt(oldRow.workOrderNum)
        const remove = this.workOrderData.splice(oldIndex, 1)[0]
      }
    },
    // 取消分解
    handleCancelDecompose() {
      this.decomposeScheduleDialog = false
    },
    // 确认分解
    async handleOkDecompose() {
      console.log(this.workOrderData)
      const find = this.workOrderData.find(e => parseInt(e.workOrderNum) === 0)
      if (find) {
        this.$modal.msgError('生产数量不为0')
        return
      }
      const reduce = this.workOrderData.reduce((acc, cur) => acc + parseInt(cur.workOrderNum), 0)
      if (reduce > this.currentSchedule.scheduleNum) {
        this.$modal.msgError('大于计划总数!')
        return
      }
      // 发送请求
      this.$modal.loading('正在分解...')
      await decomposeSchedule(this.workOrderData)
      this.$modal.closeLoading()
      this.$modal.msgSuccess('分解成功!')
      await this.$tab.refreshPage()
      this.decomposeScheduleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.my-input {
  width: 205px;
}

.my-table-header-row {
  background-color: #f8f8f9 !important;
  color: #515a6e !important;
  height: 40px;
  font-size: 13px;
  font-weight: bold;
}

.my-table-row {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  text-align: center;
  padding: 10px 0 10px 0;
  border-bottom: 1px solid #dfe6ec;
  background-color: #FFFFFF;
}
</style>
